package com.oneday.nuo.base.common;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;

import com.oneday.nuo.base.exception.NuoException;
import com.oneday.nuo.base.response.NuoErrorStatus;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 字段校验重复
 * @Author liushuai
 * @return
 * @throws
 * @Date 2021/4/25 0025 19:47
 */
public class CheckRepeat<T> {


    public Boolean queryFieldIsExist(SFunction<T, ?> field, String fieldValue, Object id, BaseMapper dao,Class<?> clazz) {
        if(StrUtil.isEmpty(fieldValue)){
            throw  new NuoException(NuoErrorStatus.PARAM_IS_NOT_NULL);
        }
        LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(field,fieldValue);
        Object entity =  dao.selectOne(wrapper);
        String oldId = "";
        try {
            Method method = clazz.getMethod("getId");
            Object obj = method.invoke(clazz.newInstance());
            oldId = String.valueOf(obj);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        if(ObjectUtil.isNotNull(entity)){
            if(oldId.equals(String.valueOf(id))){
                //查出的数据与id相等，则为修改
                return false;
            }
            //若不相等则查出的数据并不是修改内容，则为存在
        }else{
            //通过用户名未查出来数据，则不存在
            return  false;
        }
        return true;
    }
}
